import GameRule from './enum/game';
import Player from './player';
import Board from './board';
import PlayerAction from './action';
import { useContext, useState } from 'react';
import './game';
import { GameContext } from './reducer';

/**
 * @function Game 游戏主入口
 */
export default function Game () {
    /**
     * @function initPlayAction 初始化playAction数据
     * @returns {Action[]}
     */
    function initPlayAction () {
        return new Array(GameRule.MESH_COUNT).fill('')
            .map((val: string, idx: number): Action => {
                return {
                    isStart: !idx,
                    isShow: !idx,
                    action: idx ? [] : new Array(GameRule.MESH_COUNT).fill(null),
                };
            });
    }
    const { changeState } = useContext(GameContext);
    const [playAction, setPlayAction] = useState<Action[]>(initPlayAction());
    const [checkedIndex, setCheckedIndex] = useState<number>(0);
    /**
     * @function changeChecked 更新当前棋盘记录数据、当前点击步骤位置、游戏记录信息
     * @param {CheckedListData} res 子组件传递数据
     * @param {Position} position 点击位置
     */
    function changeChecked (res: CheckedListData) {
        /** 设置当前点击位置下标index，以及当前对应下标动作集合 */
        const { index, action } = {
            index: res.filter(val => val !== null).length,
            action: res,
        };
        let changeAction = [...playAction];
        changeAction = changeAction.map((val: Action, idx: number) => {
            if (idx <= index) val.isShow = true;
            else if (checkedIndex + 1 !== index && idx > index) val.isShow = false;

            if (idx === index) val.action = action;
            else if (checkedIndex + 1 !== index && idx > index) val.action = [];

            return val;
        });

        setCheckedIndex(index);
        setPlayAction(changeAction);
        changeState({ type: 'changeExecute', payload: { executeStep: index } });
        changeState({ type: 'changePlayer' });
    }
    /**
     * @function switchAction 切换游戏记录步骤时触发数据更新，更新当前游戏玩家及选中步骤对应的棋盘记录数据
     * @param {number} clickIndex 步骤下标
     */
    function switchAction (clickIndex: number) {
        const newCheckedList =  playAction[clickIndex].action;
        changeState({ type: 'setActionChecked', payload: { actionChecked: newCheckedList } });
        changeState({ type: 'switchAction', payload: { clickIndex } });
        changeState({ type: 'changeEndingState', payload: { ending: (clickIndex === checkedIndex) } });
    }

    return (<div className='game'>
        <div className='game-main'>
            <div className='player-info'>
                <Player/>
            </div>
            <div className='game-board'>
                <Board
                    changeCheckedList={changeChecked}
                />
            </div>
        </div>
        <div className='game-action'>
            <PlayerAction
                playAction={playAction}
                switchAction={switchAction} />
        </div>
    </div>);
}
